using UnityEngine;

namespace JHY.Client.Assets.Scripts.Tools
{
    public class MonoSingleTon<T> : MonoBehaviour
        where T : MonoBehaviour
    {
        public static bool IsDontDestroyOnLoad = true;
        public static GameObject monoObject;

        static T _instance;
        public static T Instance
        {
            get
            {
                if (_instance == null && monoObject == null)
                {
                    _instance = FindObjectOfType<T>();
                    if (_instance != null)
                    {
                        return _instance;
                    }
                    monoObject = new GameObject(typeof(T).Name);
                    _instance = monoObject.AddComponent<T>();
                    if (IsDontDestroyOnLoad)
                    {
                        DontDestroyOnLoad(monoObject);
                    }
                }
                else if (_instance == null && monoObject != null)
                {
                    _instance = monoObject.GetComponent<T>();
                }
                return _instance;
            }
        }
    }
}
